﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RestSharp;
using Newtonsoft.Json.Linq;
using Tradier.Models;

namespace Tradier
{
    public partial class SymbolChains : System.Web.UI.Page
    {
        protected Dictionary<string, List<ChainModel>> Chains { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            var accessToken = Session["UserTradierAccessToken"];
            if (accessToken == null)
            {
                Response.Redirect("/login.aspx");
            }
        }

        protected void OnSearchButtonClicked(object sender, EventArgs e)
        {
            try
            {

                if (!string.IsNullOrEmpty(uxSymbol.Text))
                {
                    var accessToken = Session["UserTradierAccessToken"];
                    if (accessToken == null)
                    {
                        Response.Redirect("/login.aspx");
                    }

                    var symbol = uxSymbol.Text;
                    GetChains(symbol, (string)accessToken);
                }
            }
            catch
            {
            }
        }

        private void GetChains(string symbol, string accessToken)
        {
            RestClient client = new RestClient("https://api.tradier.com");
            var request = new RestRequest(string.Format("/v1/markets/options/expirations?symbol={0}", symbol), Method.GET);
            request.AddHeader("Content-type", "application/json");
            request.AddHeader("Authorization", "Bearer " + accessToken);

            var result = (client.Execute(request).Content);
            var json = JObject.Parse(result);
            var expirations = json["expirations"];
            if (expirations.HasValues)
            {
                var dates = expirations["date"];
                Chains = new Dictionary<string, List<ChainModel>>();

                foreach (var date in dates)
                {
                    var dateString = (string)date;
                    GetChainsDetail(dateString, symbol, accessToken);
                }
            }
        }

        private void GetChainsDetail(string date, string symbol, string accessToken)
        {
            RestClient client = new RestClient("https://api.tradier.com");
            var request = new RestRequest(string.Format("/v1/markets/options/chains?symbol={0}&expiration={1}", symbol, date), Method.GET);
            request.AddHeader("Content-type", "application/json");
            request.AddHeader("Authorization", "Bearer " + accessToken);

            var result = (client.Execute(request).Content);
            var json = JObject.Parse(result);
            var options = json["options"];
            if (options.HasValues)
            {
                var chains = CreateMapping(json);
                Chains.Add(date, chains);
            }
        }

        private List<ChainModel> CreateMapping(JObject json)
        {
            var chains = json["options"]["option"];
            var chainModel = new List<ChainModel>();
            foreach (var chain in chains)
            {
                var chainItem = new ChainModel()
                {
                    Symbol = !string.IsNullOrEmpty(chain["symbol"].ToString()) ? (string)chain["symbol"] : "",
                    Strike = !string.IsNullOrEmpty(chain["strike"].ToString()) ? (float)chain["strike"] : 0,
                    Last = !string.IsNullOrEmpty(chain["last"].ToString()) ? (float)chain["last"] : 0,
                    Bid = !string.IsNullOrEmpty(chain["bid"].ToString()) ? (float)chain["bid"] : 0,
                    Ask = !string.IsNullOrEmpty(chain["ask"].ToString()) ? (float)chain["ask"] : 0,
                    Change = !string.IsNullOrEmpty(chain["change"].ToString()) ? (float)chain["change"] : 0,
                    OpenInterest = !string.IsNullOrEmpty(chain["open_interest"].ToString()) ? (int)chain["open_interest"] : 0,
                    Volume = !string.IsNullOrEmpty(chain["volume"].ToString()) ? (int)chain["volume"] : 0,
                    OptionType = !string.IsNullOrEmpty(chain["option_type"].ToString()) ? (string)chain["option_type"] : ""
                };
                chainModel.Add(chainItem);
            }
            return chainModel;
        }
    }
}